import express from 'express';
import axios from 'axios';
import dotenv from 'dotenv';
import cors from 'cors'
dotenv.config();

const app = express();
const port = process.env.PORT || 3000;
const API_KEY = 'bce-v3/ALTAK-zVxB7BFMqIVZRtCQFfEQL/1579b41d79e97207d7018601a8a9cb8ec2a03130';
const SECRET_KEY = 'e337432ba1074ec5a6a0a9d195ba7206';
// 获取 access_token 的 URL
const ACCESS_TOKEN_URL = `https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=${API_KEY}&client_secret=${SECRET_KEY}`;
// 千帆大模型平台的对话 API URL
const CHAT_API_URL = 'https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions';

app.use(cors())
//中间件，解析JSON数据
app.use(express.json());

//获取 access_token
async function getAccessToken(){
    try{
        const response=await axios.get(ACCESS_TOKEN_URL);
        return response.data.access_token;
    }catch(error){
        console.error('获取access_token失败',error);
        return null;
    }
}
//处理搜索请求的API接口
app.get('/ai/search',async(req,res)=>{
    const {query}=req.body;
    if(!query){
        return res.status(400).json({error:'查询内容不能为空'});
    }
    const accessToken=await getAccessToken();
    if(!accessToken){
        return res.status(500).json({error:'无法获取access_token'})
    }
    //调用大模型API
    try{
        const response=await axios.post(
            `${CHAT_API_URL}?access_token=${accessToken}`,
            {
                message:[
                    {
                        role:'user',
                        content:query
                    }
                ]
            },
            {
                headers:{
                    'Content-Type':'application/json'
                }
            }
        );
        const aiResponse=response.data.choices[0].message.content;
        res.json({result:aiResponse});
    }catch(error){
        console.error('调用大模型API失败',error);
        res.status(500).json({error:'调用大模型API失败'});
    }
});

//启动服务器
app.listen(port,()=>{
    console.log(`服务器已启动，监听端口${port}`);
})